import requests
import json
import logging
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler


glob_cache_session = None
cache_model_list = None
cache_token_list = None
cache_refresh_time = None
cache_model_map = None
logger = logging.getLogger('async_logger')


logger.setLevel(logging.INFO)

def get_one_api_session():
    url = f"http://{one_api_ip}:{one_api_port}/api/user/login"
    payload = {
        "username": one_api_username,
        "password": one_api_password
    }

    # 发送POST请求
    response = requests.post(url, json=payload)
    # 获取响应头中的Cookie值
    cookies = response.cookies
    session = cookies.get("session")
    return session


def analyze_channels():
    url = f"http://{one_api_ip}:{one_api_port}/api/channel/?p=0"
    # 定义请求头
    headers = {
        "Cookie": f'{glob_cache_session}'
    }
    response = requests.get(url, headers=headers)
    response_body = response.json()
    model_list = []
    channel_info_list = response_body['data']
    for channel_info in channel_info_list:
        base_url = channel_info['base_url']
        channel_name = channel_info['name']
        model_strs = str(channel_info['models']).split(",")
        for model in model_strs:
            model_item = {
                'model': model,
                'base_url': base_url,
                'channel_name': channel_name
            }
            model_list.append(model_item)
    return model_list



def analyze_tokens():
    # 从配置文件中读取参数
    with open('config.json', 'r') as config_file:
        config = json.load(config_file)
    url = f"http://{one_api_ip}:{one_api_port}/api/token/?p=0&order="
    # 定义请求头
    headers = {
        "Cookie": glob_cache_session
    }
    response = requests.get(url, headers=headers)
    response_body = response.json()
    token_info_list = response_body['data']
    return token_info_list

def refresh_cache_task():
    global glob_cache_session
    glob_cache_session = "session="+ get_one_api_session()
    global cache_model_list
    cache_model_list = analyze_channels()
    tmp_cache_model_map = {}
    for cm in cache_model_list:
        tmp_cache_model_map[cm['model']] = cm
    global cache_model_map
    cache_model_map = tmp_cache_model_map
    global cache_token_list
    cache_token_list = analyze_tokens()
    now = datetime.now()
    global cache_refresh_time
    cache_refresh_time = now.strftime("%Y-%m-%d %H:%M:%S")
    logger.info(f"刷新缓存完成 {cache_refresh_time}")

# 从配置文件中读取参数
with open('config.json', 'r') as config_file:
    config = json.load(config_file)

one_api_config = config["one-api"]
one_api_ip = one_api_config["ip"]
one_api_port = one_api_config["port"]
one_api_username = one_api_config["username"]
one_api_password = one_api_config["password"]
refresh_time_out = one_api_config["timeout"]
refresh_cache_task()
# 创建调度器
scheduler = BackgroundScheduler()

# 添加定时任务，每 5 分钟执行一次
scheduler.add_job(refresh_cache_task, 'interval', minutes=refresh_time_out)

# 启动调度器
scheduler.start()



